﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;

namespace MedicWeb.forms.Print {
    public partial class ObjectName : SessionPage {
        protected void Page_Load(object sender, EventArgs e) {

            var mainService = new MainService();
            var names = mainService.GetObjectNameDirectory(GetSession());
            var form = Request.Form;
            var allKeys = form.AllKeys;
            Dictionary<string, string> map = new Dictionary<string, string>();
            foreach (var key in allKeys) {
                var s = key.Substring(key.LastIndexOf("$") + 1);
                map[s] = form[key];
            }

            foreach (var name in names) {
                var row = new TableRow();
                var nameCell = new TableCell();
                nameCell.Width = 200;
                var valueCell = new TableCell();
                nameCell.Text = name.Object;
                var textBox = new TextBox();
                textBox.ID = name.Object;
                textBox.ClientIDMode = ClientIDMode.Static;
                textBox.Attributes.Add("runat", "Server");
                if (map.ContainsKey(name.Object)) {
                    textBox.Text = map[name.Object];
                    if (!map[name.Object].Equals(name.Name)) {
                        textBox.Attributes["changed"] = "changed";
                    }
                } else {
                    textBox.Text = name.Name;
                }
                textBox.CssClass = "fill nullable";
                valueCell.Controls.Add(textBox);
                row.Cells.Add(nameCell);
                row.Cells.Add(valueCell);
                tblNames.Rows.Add(row);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e) {
            var mainService = new MainService();
            foreach (TableRow row in tblNames.Rows) {
                var controls = row.Cells[1].Controls;
                foreach (Control control in controls) {
                    TextBox tb = (TextBox) control;
                    if (tb.Attributes["changed"] == "changed") {
                        var id = tb.ID;
                        var text = tb.Text;
                        mainService.SaveObjectName(GetSession(), new MedicService.ObjectName(){Object = id, Name = text});
                    }
                }
                //HiddenField hf = (HiddenField) .Controls[0];
                //TextBox tb = (TextBox)row.Cells[1].Controls[1];
            }
        }
    }
}